import { Component, Input, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from "@angular/forms";
import { NzMessageService } from "ng-zorro-antd";

import { FcsService } from "../../service/fcs.service";
import { Function, PublishVersionRes } from "../class/instance";
import {randomBytes} from 'crypto';

@Component({
  selector: 'app-fcs-publish',
  templateUrl: './fcs-publish.component.html',
  styleUrls: ['./fcs-publish.component.less']
})
export class FcsPublishComponent implements OnInit {
  @ViewChild('publishForm', {static: true}) publishFormComponent;
  @Input() fcsInstance;

  publishForm: FormGroup;
  disableDes:boolean = false;
  constructor(private fb: FormBuilder,
              private fcsService: FcsService,
              private msgService: NzMessageService) {

  }

  ngOnInit() {
    // 添加时间戳和随机数字段
    this.publishForm.addControl('timestamp', new FormControl(Date.now()));
    this.publishForm.addControl('nonce', new FormControl(randomBytes(5).toString(36).substring(0, 9)));

    this.publishForm = this.fb.group({
      description: ['',[Validators.maxLength(500),this.descriptionValid]]
    });
  }

  descriptionValid(control: FormControl):any{
    let des: string = control.value;
    // 最大支持500个英文字母、数字、空格、逗号、句号、中文
    let pattern = new RegExp('^[a-zA-Z0-9 ,，。.\u4e00-\u9fa5]{0,500}$');
    if(!des){
      return null;
    }
    if (!pattern.test(des)) {
      return { description:true };
    }
    return null;
  }

  /**
   * 提交表单
   *
   * @returns {boolean}
   * @memberof GroupCreateComponent
   */
  submitForm(): Promise<PublishVersionRes> {
    let group = this.publishForm as FormGroup;
    for (const i in group.controls) {
      if (i) {
        group.controls[i].markAsDirty();
        group.controls[i].updateValueAndValidity();
      }
    }
    this.disableDes = true;
    //返回一个promise对象才可以调用then等函数
    return new Promise((resolve, reject) => {
      let param: { [index: string]: any } = {};
      // 设置参数
      let description = this.publishForm.get('description').value;
      param['description']  = description;
      param['groupId'] = this.fcsInstance.groupId;
      param['funcId'] = this.fcsInstance.functionId;
      this.fcsService.createVersion(this.fcsInstance.groupId, this.fcsInstance.functionId, param).subscribe(
        data => {
          this.disableDes = false;
          if (data && data.functionName) {
            resolve({
              success: true,
              versionName:data.versionName
            });
            this.msgService.success(data['message'] || '发布成功！');
          } else {
            resolve({
              success:false,
              versionName:''
            });
            this.msgService.error(data['message']);
          }
        },
        err => {
          this.disableDes = false;
          resolve({
            success: false,
            versionName:''
          });
        });
    });
  }

}
